package com.tool.emulator.apple2.pers;

import com.tool.emulator.apple2.Apple2;
import com.tool.emulator.apple2.runtime.EmuState;
import com.tool.emulator.common.IODevice;
import com.tool.emulator.common.VirtualDevice;

//Apple2 的扩展卡
public abstract class Peripheral extends VirtualDevice implements IODevice {
	public final Apple2 apple2;
	public final int slot;
	public final int io_offset;
	protected volatile boolean installed = false;

	protected Peripheral(String name, Apple2 apple2, int slot) {
		super(name);
		this.apple2 = apple2;
		this.slot = slot;
		this.io_offset = Apple2.IO_OFFSET + 0x80 + slot * 16;
	}

	@Override
	public synchronized void deviceLoadState(EmuState emuState) throws Exception {
		boolean installed = this.isInstalled();
		super.deviceLoadState(emuState);
		if (this.isInstalled() != installed) {
			this.installed = installed;
			if (installed)
				this.uninstall();
			else
				this.install();
		}
	}

	protected abstract int[] getROM();

	public synchronized final void install() {
		if (!this.installed) {
			this.installed = true;
			apple2.BUS.initIO(this.io_offset, 16, this);
			apple2.BUS.initRom(0xC000 + this.slot * 0x100, getROM());
		}
	}

	public synchronized final void uninstall() {
		if (this.installed) {
			this.installed = false;
			apple2.BUS.initUnuse(this.io_offset, 16);
			apple2.BUS.initUnuse(0xC000 + this.slot * 0x100, 0x100);
		}
	}

	public boolean isInstalled() {
		return this.installed;
	}
}
